﻿namespace Soul.IdentityServer.Validation
{
    public interface IScopeValidator
    {
        Task<Resources> ValidationAsync(Client client, OpenIdConnectParameters parameters);
    }

    internal class ScopeValidator : IScopeValidator
    {
        private readonly IResourceStore _scopeStore;

        public ScopeValidator(IResourceStore scopeStore)
        {
            _scopeStore = scopeStore;
        }

        public async Task<Resources> ValidationAsync(Client client, OpenIdConnectParameters parameters)
        {
            List<string>? scopes;
            if (!string.IsNullOrWhiteSpace(parameters.Scope))
            {
                scopes = parameters.Scope.Split(',').ToList();
                foreach (var item in scopes)
                {
                    if (!client.AllowedScopes.Contains(item))
                    {
                        throw new ValidationException(ValidationErrors.InvalidScope, $"'{item}' is not allowed");
                    }
                }
            }
            else
            {
                scopes = client.AllowedScopes.ToList();
            }
            var resources = await _scopeStore.GetResoucesByScopesAsync(scopes);
            foreach (var item in scopes)
            {
                if (!resources.Scopes.Contains(item))
                {
                    throw new ValidationException(ValidationErrors.InvalidScope, $"'{item}' is invalid scope");
                }
            }
            return resources;
        }
    }
}
